//
//  AlbumViewController.m
//  Ting
//
//  Created by 安静的美男子 on 14/11/12.
//  Copyright (c) 2014年 安静的美男子. All rights reserved.
//

#import "AlbumViewController.h"

@interface AlbumViewController ()<UITableViewDataSource ,UITableViewDelegate>

@end

@implementation AlbumViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    
    [self getData];
    if (_DowningArr.count != 0) {
        _time = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(getData) userInfo:nil repeats:YES];
        
    }
    [self creatTable];
    [self CreatTabbar];
    
    // Do any additional setup after loading the view.
}
-(void)getData
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    _webPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Private Documents/Temp"];
    _cachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Private Documents/Cache"];
    //如果文件存在这个路径
    if ([fileManager fileExistsAtPath:_cachePath]) {
        NSError *error = nil;
        NSArray *arr = [fileManager contentsOfDirectoryAtPath:_cachePath error:
                        &error];
        if (error != nil) {
            NSLog(@"%@",error);
        }
        else
        {
            self.DownedArr = [NSMutableArray arrayWithArray:arr];
            
        }
        }
    if ([fileManager fileExistsAtPath:_webPath]) {
        NSError *error = nil;
        NSArray *arr2 = [fileManager contentsOfDirectoryAtPath:_webPath error:
                        &error];
        if (error != nil) {
            NSLog(@"%@",error);
        }
        else
        {
            self.DowningArr = [NSMutableArray arrayWithArray:arr2];
            
        }
    }
    NSInteger a = 0;
    NSInteger b = 0;
    if (_DownedArr.count != 0) {
        a = 1;
    }
    if (_DowningArr.count != 0) {
        b = 1;
    }
    _Count = a+ b;
    
    if (_Count == 0) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"暂无下载信息" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
    if (_DowningArr.count ==0) {
        [_time invalidate];
    }
    [_table reloadData];
    


}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (_Count == 2) {
        return section == 0?@"正在下载" :@"已经完成";
        
    }
    if (_Count == 1 && _DowningArr.count != 0 ) {
        return @"正在下载";
    }
    if (_Count == 1 && _DownedArr.count != 0) {
        return @"已经完成";
    }
    else
        return 0;
    
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _Count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
 
    if (_Count == 2) {
        if (section ==0) {
            return self.DowningArr.count;
        }
        if (section == 1) {
            return self.DownedArr.count;
        }
        
    }
    if (_Count == 1 && _DowningArr.count != 0) {
        return _DowningArr.count;
    }
    if (_Count == 1 && _DownedArr.count != 0) {
        return _DownedArr.count;
    }
    return 0;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_Count == 2) {
        if (indexPath.section == 0) {
            
            DownLoadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DownLoadCell"];
            if (!cell) {
                cell = [[[NSBundle mainBundle]loadNibNamed:@"DownLoadTableViewCell" owner:nil options:nil]firstObject];
                
            }
            if (_DowningArr.count != 0) {
                DownLoadManager *manager = [DownLoadManager shareManager];
                NSString *path = [_webPath stringByAppendingString:[NSString stringWithFormat:@"/%@",_DowningArr[indexPath.row]]];
                NSFileManager *fileManager = [NSFileManager defaultManager];
                long long sizes = [[fileManager attributesOfItemAtPath:path error:nil] fileSize];
                
                float value = (float)sizes/(float)manager.total;
                cell.jindu.text = [NSString stringWithFormat:@"%0.2f %%",value * 100];
                cell.title.text = _DowningArr[indexPath.row];
                
                cell.progress.progressViewStyle = UIProgressViewStyleDefault;
                cell.progress.backgroundColor = [UIColor blackColor];
                cell.progress.progress = value;
            }
            cell.title.text = _DowningArr[indexPath.row];
            cell.title.font = [UIFont systemFontOfSize:15];
            
            
            return cell;
            
        }
        if (indexPath.section == 1) {
            DownLoadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DownLoadCell"];
            if (!cell) {
                cell = [[[NSBundle mainBundle]loadNibNamed:@"DownLoadTableViewCell" owner:nil options:nil]firstObject];
                
            }
            cell.title.text = _DownedArr[indexPath.row];
            cell.progress.hidden = YES;
            cell.jindu.hidden = YES;
            return cell;
        }
       
    }else if (_Count == 1)
    {
        DownLoadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DownLoadCell"];
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"DownLoadTableViewCell" owner:nil options:nil]firstObject];
            
        }
        if (_DowningArr.count != 0) {
            DownLoadManager *manager = [DownLoadManager shareManager];
            NSString *path = [_webPath stringByAppendingString:[NSString stringWithFormat:@"/%@",_DowningArr[indexPath.row]]];
            NSFileManager *fileManager = [NSFileManager defaultManager];
            long long sizes = [[fileManager attributesOfItemAtPath:path error:nil] fileSize];
            
            float value = (float)sizes/(float)manager.total;
            cell.jindu.text = [NSString stringWithFormat:@"%0.2f %%",value * 100];
            cell.title.text = _DowningArr[indexPath.row];
            
            cell.progress.progressViewStyle = UIProgressViewStyleDefault;
            cell.progress.backgroundColor = [UIColor blackColor];
            cell.progress.progress = value;
          
        }else
        {
            cell.title.text = _DownedArr[indexPath.row];
            cell.progress.hidden = YES;
            cell.jindu.hidden = YES;
        }
        return cell;
        
    }
    return nil;
    
    
}
-(void)creatTable
{
    
    self.table = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, 320, 568 - 44 - 64) style:UITableViewStylePlain];
    _table.delegate = self;
    _table.dataSource = self;
    [self.view addSubview:_table];
    
}



-(void)CreatTabbar
{
    
    UIView *black = [[UIView alloc]initWithFrame:CGRectMake(64 * 2, 568 - 64, 64, 64)];
    [self.view addSubview:black];
    black.layer.cornerRadius = 32;
    black.clipsToBounds = YES;
    
    black.backgroundColor = [UIColor blackColor];
    
    self.play = [UIButton buttonWithType:UIButtonTypeCustom];
    
    self.play.frame = CGRectMake(0, 0, 60, 60);
    self.play.center = black.center;
    
    [self.view addSubview:self.play];
    
    self.play.layer.cornerRadius = 30;
    [self.view bringSubviewToFront:self.play];
    self.play.clipsToBounds = YES;
    [self.play addTarget:self action:@selector(GotoPlay) forControlEvents:UIControlEventTouchUpInside];
    
    [self.play sd_setBackgroundImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",self.Playmodel.coverLarge]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"123.png"]];
    
    
    
}

-(void)viewWillAppear:(BOOL)animated
{
    AudioStreamerManager *audioManager = [AudioStreamerManager shareInstanceManager];
    _Playmodel = audioManager.Mymodel;
    
    
    if (audioManager.flag) {
        
        if (!_Timer) {
            //            self.Timer = [NSTimer timerWithTimeInterval:0.01 target:self selector:@selector(zhuan) userInfo:nil repeats:YES];
            
            self.Timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(zhuan) userInfo:nil repeats:YES];
        }
        
        //将定时器加入循环
        //循环用于系统页面响应,定时器和进程
        //                [[NSRunLoop currentRunLoop] addTimer:_Timer forMode:NSDefaultRunLoopMode];
        
        
        [_Timer setFireDate:[NSDate distantPast]];
        
        
        
        
    }
    else
    {
        
        [_Timer setFireDate:[NSDate distantFuture]];
        
        //        if ([_Timer isValid]) {
        //            永久停止
        //            [self.Timer invalidate];
        //            _Timer =nil;
        //        }
        
        
    }
    
}
-(void)zhuan
{
    self.play.transform = CGAffineTransformRotate(self.play.transform,2 * M_PI / 60.0 /100);
    //    if (_model.coverLarge) {
    [self.play sd_setBackgroundImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",self.Playmodel.coverLarge]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"123.png"]];
    //    }
}

-(void)GotoPlay
{
    PlayViewController *vc = [[PlayViewController alloc]init];
    AudioStreamerManager *audioManager = [AudioStreamerManager shareInstanceManager];
    vc.model = audioManager.Mymodel;
    vc.DataSource = audioManager.Mydata;
    /**
     *  number不记录
     */
    
    //    vc.number = audioManager.num;
    vc.num = [NSString stringWithFormat:@"%ld",audioManager.num];
    
    
    [self presentViewController:vc animated:YES completion:nil];
    
}
-(void)viewDidDisappear:(BOOL)animated
{
    [self.Timer invalidate];
    _Timer =nil;
    [self.time invalidate];
    _time = nil;
    
}
-(void)GotoInformation
{
    InformationViewController *vc = [[InformationViewController alloc]init];
    [vc.navigationItem setHidesBackButton:YES];
    vc.title = @"最火播主";
    
    [self.navigationController pushViewController:vc animated:NO];
    
}
-(void)GotoFind
{
    FindViewController *vc = [[FindViewController alloc]init];
    //    [self.navigationController popToViewController:vc animated:YES];
    [vc.navigationItem setHidesBackButton:YES];
    
    [self.navigationController pushViewController:vc animated:NO];
    
    
}
-(void)GotoSetting
{
    SettingViewController *vc = [[SettingViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
